from datetime import datetime
from flask import Blueprint,request,session,jsonify,app,render_template

from sqlalchemy import text

user_bp=Blueprint('userinfo',__name__)

from project import db

import hashlib

import secrets

from sentry_sdk import capture_exception
from cryptography.fernet import Fernet

from flask import current_app as app

from .models import Message,Orderinfo,Price,User,Product


# @user_bp.route('/')
# def hello_world():
#     return 'Hello, World!'

@user_bp.route('/')
def hello_world():
    return render_template('index.html')


# 生成加密密钥
key = Fernet.generate_key()
cipher_suite = Fernet(key)
@user_bp.route('/users',methods=['GET','POST'])

def user():
    try:
        # headers = {'Content-Type': 'application/json'}
        # 从请求正文中获取用户名、性别、宽带类型和订单信息
        username = request.json['username']
        gender = request.json['gender']
        first_number = request.json['firstnumber']
        first_price = request.json['firstprice']
        broadband = request.json['broadband']
        address=request.json[ "address"]
        order_list = request.json['lists']

        # 加密电话号码和用户ID
        # encrypted_first_number = cipher_suite.encrypt(first_number.encode()).decode()
        # encrypted_user_id = cipher_suite.encrypt(str(user_id).encode()).decode()

        # 检查 first_number 是否为 11 位或者为空
        if first_number and len(first_number) != 11:
            return jsonify({'error': 'Invalid first phone number.'}), 400

        # 检查手机号是否为 11 位
        for order in order_list:
            phone_number = order['tnum']
            if phone_number and len(phone_number) != 11:
                return jsonify({'error': 'Invalid phone number.'}), 400
        #给list列表号码加密
        # encrypted_number = cipher_suite.encrypt(phone_number.encode()).decode()

        # 生成用户ID
        now = datetime.now()
        date_str = now.strftime("%Y%m%d")
        phone_prefix = first_number[-4:]
        user_id = int(f"{date_str}{phone_prefix}")
        # encrypted_user_id = cipher_suite.encrypt(str(user_id).encode()).decode()

        # 查询 user 表，获取该用户对应的用户ID
        user = User.query.filter_by(username=username, gender=gender, broadband=broadband,address=address).first()
        if user is None:
            # 如果该用户不存在，插入一条新记录
            user = User(username=username, gender=gender, broadband=broadband,address=address,userid=user_id)
            db.session.add(user)
            db.session.commit()

        # 获取该用户对应的用户ID
        user_id = user.userid
        # 插入第一个订单到 products 表中
        product1 = Product(phone_number=first_number, price=first_price, broadband=broadband, userid=user_id)
        db.session.add(product1)
        db.session.commit()
        # 插入第一个订单到 products 表中
        # product1 = Product(phone_number=encrypted_first_number, price=first_price, broadband=broadband, userid=user_id)
        # db.session.add(product1)
        # db.session.commit()

        # 为每个订单插入一条记录到 products 表中
        total_price = int(first_price)
        for order in order_list:
            phone_number = order['tnum']
            price = order['price']
            if isinstance(price, str) and price.strip():
                price = int(price)
            else:
                price = 0
            product = Product(phone_number=phone_number, price=price, broadband=broadband, userid=user_id)
            total_price += price
            db.session.add(product)

        # 更新订单的总价格
        Product.query.filter_by(userid=user_id).update({'total_price': total_price})

        # # 更新用户的 total_price
        # Product.total_price = total_price

        db.session.commit()

        # return 'Order added successfully'
        # return jsonify({'user_id': user_id})
        # return user_id
        return str(user_id)

    except Exception as e:
        print(e)
        capture_exception(e)
        return {"err": repr(e)}

@user_bp.route('/order',methods=['POST','GET'])

def order():
    try:
        # 验证前端传递的json数据的正确性
        if not request.is_json:
            return {'error': 'Data is not in JSON format'}

        # 获取前端传入的userid和package_id
        user_id = request.json.get('userid')
        package_id = request.json.get('package_id')

        # 确保数据库中存在对应的用户信息和套餐信息
        user_info = User.query.filter_by(userid=user_id).first()
        if not user_info:
            return {'error': 'User does not exist'}
        package_info = Price.query.filter_by(id=package_id).first()
        if not package_info:
            return {'error': 'Package does not exist'}
        product_info = Product.query.filter_by(userid=user_id).first()
        if not product_info:
            return {'error': 'Product does not exist'}

        # 自动生成订单号
        order_id = str(user_info.userid) + str(package_info.id)

        # 在调用变量的属性之前对它们进行NoneType检查
        if not user_info or not package_info or not product_info:
            return {'error': 'User, package or product info is missing'}

        # 创建订单对象并保存到数据库
        new_order = Orderinfo(
            id=order_id,
            # create_user=user_info.name,
            # create_id=user_info.work_id,
            package_id=package_info.id,
            user_price=product_info.total_price,
            package_price=package_info.content_price,
            userid=user_info.userid,
            customer_name=user_info.username,
            address=user_info.address,
            haoma=product_info.phone_number,
            createTime=datetime.now()
        )
        db.session.add(new_order)
        db.session.commit()

        # 返回订单号
        return {'order_id': order_id}
    except Exception as e:
        print(e)
        capture_exception(e)
        return {"err": repr(e)}

@user_bp.route('/zhanshi',methods=['POST','GET'])

def zhanshi():
    try:
        orders=Orderinfo.query.all()
        order_list=[]
        for order in orders:
            order_dict = {
                # 'id': order.id,
                'create_user': order.create_user,
                # 'create_id': order.create_id,
                # 'package_id': order.package_id,
                'package_price': order.package_price,
                'user_price': order.user_price,
                # 'userid': order.userid,
                'customer_name': order.customer_name,
                'haoma': order.haoma,
                'address': order.address,
                'createTime': order.createTime
            }
            order_list.append(order_dict)
        return jsonify(order_list)
    except Exception as e:
        print(e)
        capture_exception(e)
        return {"err": repr(e)}

@user_bp.route('/commit', methods=['POST'])
def commit():
    try:
        data = request.json
        username = data.get('userName')
        orders = Message.query.filter_by(userName=username).all()
        total_price = sum([order.price for order in orders])
        result = {'orders': [{'phoneNumber': order.phoneNumber, 'price': order.price} for order in orders],
                  'total_price': total_price}

        # 从数据库中获取需要更新的模型对象
        total_price_obj = Message.query.first()

        # 更新模型对象的属性值
        total_price_obj.total_price = total_price

        # 提交更新
        db.session.commit()
        return jsonify(result)



    except Exception as e:
        print(e)
        capture_exception(e)
        return {"err": repr(e)}


@user_bp.route('/orderinfo', methods=['GET'])                             #通过订单编号获取订单信息
def get_orderinfo():
    try:
        order_info_id = request.json.get('order_info_id')
        orderinfo = Orderinfo.query.filter_by(id=order_info_id).first()
        if not orderinfo:
            return jsonify({'message': 'Orderinfo not found'})
        result = {
            'id': orderinfo.id,
            'create_user': orderinfo.create_user,
            'create_id': orderinfo.create_id,
            'package_id': orderinfo.package_id,
            'total_price': orderinfo.total_price,
            'userphone_info_id': orderinfo.userphone_info_id,
            'customer_id': orderinfo.customer_id,
            'address': orderinfo.address,
            'createTime': orderinfo.createTime,
            'statusTime': orderinfo.statusTime
        }
        return jsonify(result)
    except Exception as e:
        print(e)
        capture_exception(e)
        return {"err": repr(e)}


@user_bp.route('/price/id', methods=['GET'])             #套餐id获取相应的套餐
def get_price():
    try:
        price_info_id = request.json.get('price_id')
        price_info = Price.query.filter_by(id=price_info_id).first()
        if price_info:
            result = {
                'id': price_info.id,
                'content_price': price_info.content_price,
                'flow': price_info.flow,
                'voice': price_info.voice,
                'sms': price_info.sms,
                'speed': price_info.speed,
                'sub_card': price_info.sub_card
            }
            return jsonify(result)
        else:
            return jsonify({'error': '套餐不存在'})
    except Exception as e:
        print(e)
        capture_exception(e)
        return {"err": repr(e)}




